import time
from threading import Thread

from cf.pressure_sensor import PressureSensor

TARE_CMD = "get_tare\r\n"
TARE_CMD_SUCCESS_RES = "success\r\n"
TARE_PORT = "/dev/ttyS4"
RESET_CMD = "reset"
RESET_CMD_SUCCESS_RES = "success\r\n"


# 去皮代码
class Tare:
    def __init__(self, printer, gcmd, timeout=20.0):
        self.toolhead = printer.lookup_object('toolhead')
        self.reactor = printer.get_reactor()
        self.tared = False
        self.err = None
        self.timeout = timeout
        self.gcmd = gcmd
        self.open()

    def update_test(self):
        pass

    def open(self):
        try:
            ps = PressureSensor(port=TARE_PORT)
            ps.open()
            self.ps = ps
            self.gcmd.respond_info("OPEN /dev/ttyS4 Sucessful\r\n")
            #self.run()
        except Exception as e:
            help.log(f"TareReset open {e}")
            self.gcmd.respond_info("OPEN /dev/ttyS4 False\r\n")
            raise self.gcmd.error(f"TareReset open, {e}")

    def _run(self):

        res = self.ps.send_cmd_with_res(TARE_CMD)

        if TARE_CMD_SUCCESS_RES in res:
            self.gcmd.respond_info("tare success")
            self.tared = True
        elif "fail" in res:
            self.gcmd.respond_info("tare fail")
            res = self.ps.send_cmd_with_res(TARE_CMD)
            if TARE_CMD_SUCCESS_RES in res:
                self.gcmd.respond_info("tare success")
                self.tared = True
            elif "fail" in res:
                self.gcmd.respond_info("tare fail")
                raise self.command_error(f"tare fail")
        else:
            self.gcmd.respond_info("tare connect fail")
            raise self.command_error(f"connect fail")
        
        #try:
        #    self.gcmd.respond_info("tare start")
        #    res = self.ps.send_cmd_with_res(TARE_CMD, re_try=3)
        #    if "fail" in res:
        #        res = self.ps.send_cmd_with_res(TARE_CMD, re_try=1)
        #    if TARE_CMD_SUCCESS_RES not in res:
        #        self.err = f"tare fail res:{res}"
        #   self.gcmd.respond_info(
        #        f"tare res: {res}")
        #except Exception as e:
        #    self.err = e
        #    help.log(f"tare fail, {e}")
        #finally:
        #    self.tared = True


    def run(self):
        self.tared = False
        self.err = None
        self.gcmd.respond_info(
            f"tareTask start")
        try:
            self.toolhead.wait_moves()
            Thread(target=self._run).start()
            tare_start = time.time()
            while not self.tared:
                if time.time() - tare_start > self.timeout:                    
                    raise self.command_error(f"tare fail, timeout")
                eventtime = self.reactor.monotonic()
                self.reactor.pause(eventtime + 1.000)
        except Exception as e:
            raise self.gcmd.error(f"tare fail, {e}")
        finally:
            if self.ps:
                try:
                    self.ps.close()
                except Exception as e:
                    pass

        if self.err:
            raise self.gcmd.error(f"tare fail, {self.err}")


class TareReset:
    def __init__(self, printer, gcmd, timeout=3.0):
        self.toolhead = printer.lookup_object('toolhead')
        self.reactor = printer.get_reactor()
        self.finished = False
        self.err = None
        self.timeout = timeout
        self.gcmd = gcmd
        self.open()

    def open(self):
        try:
            ps = PressureSensor(port=TARE_PORT)
            ps.open()
            self.ps = ps
            self.gcmd.respond_info("OPEN /dev/ttyS4 Sucessful\r\n")
            self._run()
        except Exception as e:
            help.log(f"TareReset open {e}")
            self.gcmd.respond_info("OPEN /dev/ttyS4 False\r\n")
            raise self.gcmd.error(f"TareReset open, {e}")

    def _run(self):
        #try:
        #    self.gcmd.respond_info("TareReset start")
        self.ps.send_cmd_with_res(RESET_CMD)
        #    if "fail" in res:
        #        res = self.ps.(RESET_CMD, re_try=1)
        #    if RESET_CMD_SUCCESS_RES not in res:
        #        self.err = f"TareReset fail res:{res}"
        #    self.gcmd.respond_info(
        #        f"TareReset res: {res}")
        #except Exception as e:
        #    self.err = e
        #    help.log(f"TareReset fail, {e}")
        #finally:
        #    self.finished = True

    def run(self):
        try:
            self.toolhead.wait_moves()
            Thread(target=self._run).start()
            task_start = time.time()
            while not self.finished:
                if time.time() - task_start > self.timeout:
                    raise self.gcmd.error(f"TareReset fail, timeout")
                eventtime = self.reactor.monotonic()
                self.reactor.pause(eventtime + 0.100)
        except Exception as e:
            raise self.gcmd.error(f"TareReset fail, {e}")
        if self.err:
            raise self.gcmd.error(f"TareReset fail, {self.err}")
